from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.views.decorators.cache import never_cache
from django.core.urlresolvers import reverse
from .form_fileupload import UploadFileForm
from news.models import Article, Reporter
from .form_reporter import ReporterForm
from contacts.common_me import (print_request_user,
                                print_request_cookie,
                                print_request_session,
                                )

def year_archive(request, year):
    a_list = Article.objects.filter(pub_date__year = year)
    print_request_user(request)
    print_request_session(request)

    return render_to_response('news/year_archive.html',
                              {'year': year,
                               'article_list': a_list,
                               })

def month_archive(request, year, month):
    # print type(month), month
    print_request_user(request)
    print_request_session(request)
    print_request_cookie(request)

    if 0 < int(month) < 13:
        a_list = Article.objects.filter(pub_date__year = year,
                                        pub_date__month = month)
        return render_to_response('news/month_archive.html',
                                  {'year': year,
                                   'month': month,
                                   'article_list': a_list})
    else:
        return HttpResponseRedirect('/news/articles/' + year + '/')

def day_article(request, year, month, day):
    print_request_user(request)

    if request.session.get('member_id', None):
        print "DEBUG(request.session:", request.session.items()
    if 0 < int(month) < 13:
        if 0 < int(day) < 31:
            a_list = Article.objects.filter(pub_date__year = year,
                                            pub_date__month = month)
            return render_to_response('news/day_archive.html',
                                      {'year': year,
                                       'month': month,
                                       'day': day,
                                       'article_list': a_list})

            pass
        else:
            return HttpResponseRedirect('/news/articles/' + year + '/' + month + '/')
    else:
        return HttpResponseRedirect('/news/articles/' + year + '/')

def upload_file(request):
    # print "____request session Begin:"
    # for key,value in request.session.items():
    #     print key,value
    # print "____reqeust session END."
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        print request.FILES
        if form.is_valid():
            print "valid ok"
            handle_uploaded_file(request.FILES['file'])
            return HttpResponseRedirect('/news/articles/2014/')
        else:
            print request.META['HTTP_REFERER']
            return HttpResponseRedirect(request.META['HTTP_REFERER'])
    else:
        form = UploadFileForm()
    return render_to_response('news/upload.html',
                              {'form': form},
                              context_instance = RequestContext(request))

def handle_uploaded_file(f):
    with open('upload.txt', 'wb+') as dest_file:
        for chunk in f.chunks():
            dest_file.write(chunk)

@never_cache
def login(request):
    print_request_user(request)
    # if hasattr(request, 'user'):
    #     print "DEBUG(request.user: %s" % request.user
    print_request_session(request)
    # if request.session.get('member_id', None):
    #     print "DEBUG(request.session:", request.session.items()
    message = {}
    if request.method == "POST":
        try:
            m = Reporter.objects.get(full_name = request.POST['full_name'])
        except Reporter.DoesNotExist:
            message = {'warn_color': 'red',
                       'msg': "username or password is error."
                       }
            return render_to_response('news/login.html',
                                      {'message': message,
                                       'form': ReporterForm(),
                                       },
                                      context_instance = RequestContext(request))
        print "DEBUG(login user: %s" % m
        if m and m.password == request.POST['password']:
            request.session['member_id'] = m.id
            request.user = request.POST['full_name']
            message = {'warn_color': '',
                       'msg': "Successed.",
                       }
            response =  render_to_response('news/year_archive.html',
                                           {'message': message,
                                            'year': 2014,
                                            'article_list': Article.objects.filter(pub_date__year = 2014)
                                            })
            response.set_cookie("user_name", request.POST['full_name'])
            return response
        else:
            message = {'warn_color': 'red',
                       'msg': "username or password is error."
                       }
    else:   # show login form
        return render_to_response('news/login.html',
                                  {'message': message,
                                   'form': ReporterForm(),
                                   },
                                  context_instance=RequestContext(request),
                                  )

def logout(request):
    try:
        if hasattr(request.session, 'member_id'):
            print "DEBUG(before logout: %s" % request.session['member_id']

        print_request_user(request)
        if request.user != "AnonymousUser":
            from django.contrib.auth.models import AnonymousUser
            print "DEBUG(change request.user to AnonymousUser"
            request.user = AnonymousUser()
        request.session.flush()
        # return HttpResponse("You are not loggin.")
        return HttpResponseRedirect(reverse('news:login'))
    except KeyError:
        return HttpResponse("You are not loggin.(errors?)")
    return HttpResponse("You're logged out.")
